package cn.lctvu.servlet.client;

import cn.lctvu.bean.News;
import cn.lctvu.service.ItemService;
import cn.lctvu.service.NewsService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/findNewsByid")
public class findNewsByid extends HttpServlet {
    //调用 service
    private NewsService newsService=new NewsService();
    private ItemService itemService=new ItemService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        String id=request.getParameter("id");
        if(id!=null){
            // 根据id查找News
           News news=newsService.getNewsById(Integer.parseInt(id));
           if(news!=null){
               request.setAttribute("news",news);
               //得到栏目名称，并保存在request域对象中
               request.setAttribute("items",itemService.getItemById(news.getItemid()));
               RequestDispatcher dispatcher=
                       request.getRequestDispatcher("/content.jsp");
               dispatcher.forward(request,response);
           }else {
               out.print("<script language='javascript'>alert('文章不存在');" +
                       "document.location.href='/IndexServlet';</script>");
               return;
           }
        }else {
            out.print("<script language='javascript'>alert('没有权限访问;');" +
                    "document.location.href='/IndexServlet';</script>");
            return;
        }
    }
}
